package com.example.itcacp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.itcacp.entity.Content;
import com.example.itcacp.entity.Like;
import com.example.itcacp.repository.mybatis.CollectMapper;
import com.example.itcacp.repository.mybatis.ContentMapper;
import com.example.itcacp.repository.mybatis.LikeMapper;
import com.example.itcacp.service.ContentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements ContentService {

    @Resource
    private ContentMapper contentMapper;

    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private String serverPort;

    @Value("${image.upload.temp.path}")
    private String tempUploadPath;

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private CollectMapper collectMapper;


    /**
     * 查询全部
     * */
    @Override
    public List<Content> selectContentAll(Like.ContentType contentType) {
        return contentMapper.selectContentAll ( contentType );
    }

    /**
     * 内容作者同类型作品查询
     * */
    @Override
    public List<Content> selectContentAllByUser(Like.ContentType contentType, Long userId) {
        return contentMapper.selectContentAllByUser ( contentType, userId );
    }

    /**
     * 分页查询
     * */
    @Override
    public PageInfo<Content> selectContentPage(Integer pageNum, Integer pageSize, Like.ContentType contentType) {
        PageHelper.startPage ( pageNum, pageSize );
        List<Content> contentList =  contentMapper.selectContentAll(contentType);
        return PageInfo.of ( contentList );
    }

    /**
     * 查询内容详情
     * */
    @Override
    public Content findContentDetailById(Long contentId, Like.ContentType contentType, Long userId) {
        Content content = contentMapper.findContentByIdType ( contentId, contentType );
        // 查询用户点赞状态
        if (userId != null) { // 如果用户存在且存在点赞/收藏数据则将状态修改为true
            Integer isLiked = likeMapper.isLiked(userId, contentId, contentType);
            content.setLikeStates (isLiked > 0);
            Integer isCollect = collectMapper.isCollect ( userId, contentId, contentType );
            content.setCollectStates ( isCollect > 0 );
        } else {
            content.setLikeStates ( false );  // 游客浏览时点赞/收藏状态为false
            content.setCollectStates ( false );
        }
        return content;
    }

    /**
     * 上传缓存图片
     * */
    @Override
    @Transactional
    public String uploadImage(MultipartFile file) throws IOException{
        // 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID() + fileExtension;
        // 构建文件存储路径（确保目录存在）
        Path uploadDir = Paths.get(tempUploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }
        Path filePath = uploadDir.resolve(uniqueFileName);
        // 保存文件到服务器
        Files.write(filePath, file.getBytes());
        // 生成可访问的图片URL（注意端口和路径匹配前端需求）
        return "http://" + serverAddress + ":" + serverPort + "/temp/" + uniqueFileName;
    }

    /**
     * 内容添加
     *
     * @return
     */
    @Override
    @Transactional
    public void add(Content content) {
        contentMapper.add ( content );
    }

    /**
     * 根据内容Id列表查询对应内容
     * */
    @Override
    public List<Content> selectContentByIds(List<Long> contentIds) {
        if (contentIds == null || contentIds.isEmpty ()) {
            return Collections.emptyList ();
        }
        return contentMapper.selectBatchIds ( contentIds );
    }

    @Override
    public PageInfo<Content> selectContentAllByUser(Integer pageNum, Integer pageSize, Long userId) {
        PageHelper.startPage ( pageNum, pageSize );
        List<Content> contentList =  contentMapper.selectContentAllByUserId(userId);
        return PageInfo.of ( contentList );
    }

    @Override
    public List<Content> selectContentAllByUser(Long userId) {
        return contentMapper.selectContentAllByUserId ( userId );
    }

    @Override
    public List<Content> searchContent(String content, Long userId) {
        return contentMapper.searchContent(content, userId);
    }

    @Override
    public List<Content> search(String query) {
        return contentMapper.search ( query );
    }
}
